#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "armsdkerr.h"
#include "armsdkcmdterm.h"
#include "uart.h"
#include "esp8266.h"

INT4 esp8266Cmd()
{
    CHR u1Cmd[CMD_BUF_LEN] = {0};

    reset_terminal_but_sig();   //恢复终端模式

    while(TRUE)
    {
        PRINTF("(esp8266)> ", u1Cmd);
        fgets(u1Cmd, CMD_BUF_LEN, STDIN);
        if (u1Cmd != NULL)
        {
            if (u1Cmd[0] == '\n')
            {
                continue;
            }

            u1Cmd[strlen(u1Cmd) - 1] = '\0';
            if (MEMCMP(u1Cmd, "quit", 4) == 0)
            {
                break;
            }

            sprintf(u1Cmd + strlen(u1Cmd), "%s", "\r\n");
            uartWrite(u1Cmd);
            usleep(100000);

            if (MEMCMP(u1Cmd, "AT+CIPSEND", strlen(u1Cmd)) == 0)
            {
                while(TRUE)
                {
                    PRINTF("> ", u1Cmd);
                    MEMSET(u1Cmd, 0, CMD_BUF_LEN);
                    fgets(u1Cmd, CMD_BUF_LEN, STDIN);

                    if (u1Cmd != NULL)
                    {
                        u1Cmd[strlen(u1Cmd) - 1] = '\0';

                        uartWrite(u1Cmd);
                        usleep(100000);

                        if (MEMCMP(u1Cmd, "+++", 3) == 0)
                        {
                            break;
                        }

                        uartRead(u1Cmd);
                        PRINTF("%s\n", u1Cmd);
                    }
                }
                MEMSET(u1Cmd, 0, CMD_BUF_LEN);
                continue;
            }

            /*uartClearFirstLine();*/
            uartRead(u1Cmd);
            PRINTF("%s\n", u1Cmd);
        }
        MEMSET(u1Cmd, 0, CMD_BUF_LEN);
    }

    set_unbuffered_input();
    return SUCCESS;
}




